package com.tsingteng.cosfun.utils;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.os.Build;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.TextView;

import com.tsingteng.cosfun.callback.OnPlayDetailClickListener;
import com.tsingteng.cosfun.ui.message.comment.usercomment.UserCommentAdapter;
import com.tsingteng.cosfun.ui.message.geneal.PlayDetailsAdapter;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static android.content.Context.ACTIVITY_SERVICE;

/**
 * 描述:
 * 创建人: 肖利
 * 时间: 2018/7/30
 * qq: (872179966)
 */

public class StringUtils {

    private static long lastClickTime;
    public static Map<String, String> txtIdMap = new HashMap<String, String>();
    public static String splitString(String text, String regex) {
        if (text.isEmpty()) return "   ";
        String[] split = text.split(regex);
        return split[0];
    }

    public static String formatZanCount(int count) {
        if (count < 10000) {
            return count + "";
        } else if (count < 10000000) {
            int w = count / 10000;
            int q = count / 1000;
            return w + "." + q + "w";
        } else {
            int w = count / 10000;
            return w + "w";
        }
    }

    /**
     * 提供（相对）精确的除法运算。当发生除不尽的情况时，由scale参数指
     * 定精度，以后的数字四舍五入。
     * @param v1 被除数
     * @param v2 除数
     * @param scale 表示表示需要精确到小数点以后几位。
     * @return 两个参数的商
     */
    public static double div(long v1, long v2, int scale) {
        if (scale < 0) {
            throw new IllegalArgumentException(
                    "The scale must be a positive integer or zero");
        }
        BigDecimal b1 = new BigDecimal(Double.toString(v1));
        BigDecimal b2 = new BigDecimal(Double.toString(v2));
        return b1.divide(b2, scale, BigDecimal.ROUND_HALF_UP).doubleValue();
    }

    /**
     * webview 设置
     * @param mVWv
     * @param activity
     */
    public static void setWebSettings(WebView mVWv, Activity activity){
        WebSettings mWebSettings = mVWv.getSettings();
        mWebSettings.setAllowFileAccess(true);
        mWebSettings.setAllowFileAccess(true);
        mWebSettings.setAppCacheEnabled(true);
        mWebSettings.setDomStorageEnabled(true);
        mWebSettings.setDatabaseEnabled(true);
        mWebSettings.setJavaScriptEnabled(true);
        mWebSettings.setAppCacheMaxSize(1024 * 1024 * 8);
        mWebSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        mWebSettings.setPluginState(WebSettings.PluginState.ON);
        mWebSettings.setUseWideViewPort(true);
        mWebSettings.setLoadWithOverviewMode(true);
        mWebSettings.setBuiltInZoomControls(true);
        mWebSettings.setSupportZoom(true);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            mWebSettings.setMixedContentMode(
                    WebSettings.MIXED_CONTENT_COMPATIBILITY_MODE);
        }
        String appCachePath = activity.getApplicationContext().getCacheDir().getAbsolutePath();
        mWebSettings.setAppCachePath(appCachePath);
        mWebSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
    }

    //按钮点击频率控制
    public static boolean isFastDoubleClick(int duration) {
        long time = System.currentTimeMillis();
        long timeD = time - lastClickTime;
        if (0 < timeD && timeD < duration) {//500毫秒内按钮无效，这样可以控制快速点击，自己调整频率
            lastClickTime = time;
            return true;
        }

        return false;
    }
    public static String matchReplaceTxt(String s) {
        String back = s;
        final String r = "<nickName.*?cosfun>";
        SpannableString spannableString = new SpannableString(back);
        Pattern pattern = Pattern.compile(r);
        Matcher matcher = pattern.matcher(spannableString);
        try {
            while (matcher.find()) {
                final String n = matcher.group(0);
                if (n != null) {
                    String name = n.substring(n.indexOf("@") + 1, n.indexOf("&"));
                    String id = n.substring(n.lastIndexOf("@") + 1, n.indexOf("%"));
                    if (back.indexOf(n) > -1) {
                        back = back.replace(n, "@" + name + " ");
                        txtIdMap.put("@" + name.trim(), id);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return back;
    }
    /**
     * 设置微博内容样式
     *
     * @param source
     * @param textView
     * @return
     */
    public static SpannableString getWeiBoContent(String source, TextView textView,PlayDetailsAdapter.OnPlayDetailClickListener onItemClickListener) {
        SpannableString spannableString = new SpannableString(source);
        String s = "@[\u4e00-\u9fa5\\w]+";
        s = "@(.*?)\\s";
        Pattern pattern = Pattern.compile(s);
        Matcher matcher = pattern.matcher(spannableString);
        if (matcher.find()) {
            textView.setMovementMethod(LinkMovementMethod.getInstance());
            matcher.reset();
        }

        while (matcher.find()) {
            final String at = matcher.group(0);
            if (at != null) {
                int start = matcher.start();
                int end = matcher.end();
                MyClickableSpan clickableSpan = new MyClickableSpan() {

                    @Override
                    public void onClick(View widget) {
                        if (onItemClickListener != null) {
                            if (!TextUtils.isEmpty(txtIdMap.get(at.trim())))
                                onItemClickListener.onUserClick(txtIdMap.get(at.trim()));
                        }
                    }
                };
                spannableString.setSpan(clickableSpan, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            }


        }

        return spannableString;
    }
    /**
     * 设置微博内容样式
     *
     * @param source
     * @param textView
     * @return
     */
    public static SpannableString getWeiBoContents(String source, TextView textView,OnPlayDetailClickListener onItemClickListener) {
        SpannableString spannableString = new SpannableString(source);
        String s = "@[\u4e00-\u9fa5\\w]+";
        s = "@(.*?)\\s";
        Pattern pattern = Pattern.compile(s);
        Matcher matcher = pattern.matcher(spannableString);
        if (matcher.find()) {
            textView.setMovementMethod(LinkMovementMethod.getInstance());
            matcher.reset();
        }

        while (matcher.find()) {
            final String at = matcher.group(0);
            if (at != null) {
                int start = matcher.start();
                int end = matcher.end();
                MyClickableSpan clickableSpan = new MyClickableSpan() {

                    @Override
                    public void onClick(View widget) {
                        if (onItemClickListener != null) {
                            if (!TextUtils.isEmpty(txtIdMap.get(at.trim())))
                                onItemClickListener.onUserClick(txtIdMap.get(at.trim()));
                        }
                    }
                };
                spannableString.setSpan(clickableSpan, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            }


        }

        return spannableString;
    }
    /**
     * 设置微博内容样式
     *
     * @param source
     * @param textView
     * @return
     */
    public static SpannableString getWeiBoContents(String source, TextView textView,UserCommentAdapter.OnPlayDetailClickListener onItemClickListener) {
        SpannableString spannableString = new SpannableString(source);
        String s = "@[\u4e00-\u9fa5\\w]+";
        s = "@(.*?)\\s";
        Pattern pattern = Pattern.compile(s);
        Matcher matcher = pattern.matcher(spannableString);
        if (matcher.find()) {
            textView.setMovementMethod(LinkMovementMethod.getInstance());
            matcher.reset();
        }

        while (matcher.find()) {
            final String at = matcher.group(0);
            if (at != null) {
                int start = matcher.start();
                int end = matcher.end();
                MyClickableSpan clickableSpan = new MyClickableSpan() {

                    @Override
                    public void onClick(View widget) {
                        if (onItemClickListener != null) {
                            if (!TextUtils.isEmpty(txtIdMap.get(at.trim())))
                                onItemClickListener.onUserClick(txtIdMap.get(at.trim()));
                        }
                    }
                };
                spannableString.setSpan(clickableSpan, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
        }

        return spannableString;
    }
    /**
     * 判断某个界面是否在前台
     *
     * @param context   Context
     * @param className 界面的类名
     * @return 是否在前台显示
     */
    public static boolean isForeground(Context context, String className) {
        if (context == null || TextUtils.isEmpty(className))
            return false;
        ActivityManager am = (ActivityManager) context.getSystemService(ACTIVITY_SERVICE);
        if (null ==am){
            return false;
        }
        List<ActivityManager.RunningTaskInfo> list = am.getRunningTasks(1);
//        boolean flag=false;
        for (ActivityManager.RunningTaskInfo taskInfo : list) {
            if (taskInfo.topActivity.getShortClassName().contains(className)) { // 说明它已经启动了
//                flag = true;
                return true;
            }
        }
        return false;
    }
}
